#!/usr/bin/env python3
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
import time
import random
import demjson

call_prix_dict = {
    '1': '90000011',  # 广州
    '2': '90000013',  # 东莞
    '3': '90000012'  # 佛山
}


def handler(session, args):  # args is string
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")

    if args is None:
        freeswitch.console_log("info", "call %s has no target call number in args param\n" % uuid)
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "call %s args string is: %s \n" % (uuid, args))

    X_city = session.getVariable("sip_h_X-city")

    if X_city is None:
        freeswitch.console_log("info", "city is required ! \n")
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "city type str: %s \n" % isinstance(X_city, str))

    X_city = X_city.strip()

    freeswitch.consoleLog("info", "call %s extend params: X_city: %s \n" % (uuid, X_city))
    try:

        session.setVariable("continue_on_fail", "false")
        session.setVariable("hangup_after_bridge", "true")
        session.setVariable("jitterbuffer_msec", "260:400:20")
        session.setVariable("rtp_jitter_buffer_during_bridge", "true")
        session.execute("export", "session_id=${uuid}")
        session.execute("export", "call_timeout=60")
        # TODO ????勾无效？
        session.setHangupHook("hangup_hook")
        # save record file
        today = time.strftime("%Y%m%d", time.localtime())

        record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                                  "/cloudcall_file/rec_20051/freeswitchRecordFile/"]
        path = random.choice(record_save_base_paths) + today + "/" + uuid + ".wav"
        freeswitch.console_log("info", "choice path: %s" % path)
        session.execute("export", "nolocal:execute_on_answer=record_session " + path)
        caller_id_number = call_prix_dict[X_city]
        # TODO 按城市设置主叫号码-----
        call_str = "{origination_caller_id_number=%s, origination_caller_id_name=s%s}sofia/internal/%s@39.108.194.175:5060" % (
        caller_id_number, caller_id_number, args)
        freeswitch.console_log("info", "bridge string is: %s \n" % call_str)
        # session.execute("bridge", "user/%s" % args)
        session.execute("bridge", call_str)
        session.hangup()
    except Exception as err:
        freeswitch.console_log("err", "call %s exception,msg: %s \n" % (uuid, str(err)))
        session.hangup("ORIGINATOR_CANCEL")


def hangup_hook(uuid):
    freeswitch.console_log("info", "myHangupHook, uuid: %s!!\n" % uuid)
    return "Result"
